<?php

namespace App\Http\Controllers\Internal;

use App\Exceptions\InvalidNonceException;
use App\Models\User;
use Sonata\GoogleAuthenticator\GoogleAuthenticator;

class UserController extends Controller
{
    /*
     * @api post /internal/nonce/check 随机码验证
     * @version 0.0.1
     * @group internal
     *
     * @param body string userId 用户ID
     * @param body string nonce 随机码
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function checkNonce()
    {
        $this->validate($this->request, [
            'userId' => 'required',
            'nonce' => 'required'
        ]);
        $nonce = $this->request->input('nonce');
        $userId = $this->request->input('userId');
        $secret = User::where('id', $userId)->value('secret');
        $googleAuth = new GoogleAuthenticator();
        if (!$googleAuth->checkCode($secret, $nonce)) {
            throw new InvalidNonceException();
        }
        return $this->sendSuccessJson();
    }
}
